<template>
  <div>
    <div class="notice-container">
      <div class="notice-box" @click="checkNotice">
        <svg class="icon" aria-hidden="true"><use xlink:href="#icon-tongzhi"></use></svg>
        {{ notice }}
      </div>
    </div>
    <div class="title-imgs-container">
      <el-carousel height="200px" :autoplay="false">
        <el-carousel-item>
          <img class="title-img" src="../../assets/banner1.jpg">
        </el-carousel-item>
        <el-carousel-item>
          <img class="title-img" src="../../assets/banner2.jpg">
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="menu-list-container">
      <div class="menu-item" v-for="m in menu" @click="m.navigation" :style="{ backgroundColor: m.color }">
        <svg class="icon" aria-hidden="true"><use :xlink:href="m.icon"></use></svg>
        {{ m.name }}
      </div>
    </div>
    <div class="status-card" v-loading="loadingCard">
      <div id="dayPercent"></div>
      <div class="date-box">{{ date }}</div>
      <div class="status-content">
        <div class="today-income">
          <div class="today-title">
            <span>今日总收入</span>
          </div>
          <div class="today-num" style="color: #1D8704;">￥{{ todayIncome }}</div>
        </div>
        <div class="today-expense">
          <div class="today-title">
            <span>今日总支出</span>
          </div>
          <div class="today-num" style="color: #870101;">￥{{ option.series[0].data[1].value }}</div>
        </div>
        <div class="family-more">
          <div class="more-txt" style="margin-right: 20px;" @click="router.push('/home/edit');">
            详情
            <svg class="icon" aria-hidden="true"><use xlink:href="#icon-you1"></use></svg>
          </div>
          <div class="more-txt" @click="router.push('/p/family');">
            家庭成员
            <svg class="icon" aria-hidden="true"><use xlink:href="#icon-you1"></use></svg>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-tips">已经到底了 :)</div>
  </div>
</template>

<script setup>
  import * as echarts from 'echarts';
  import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
  import { useUserStore } from '@/stores/user';
  import { getTodayInfo, getMonthInfo } from '@/utils/api';
  import { useRouter } from 'vue-router';
  import message from '@/utils/message';

  const router = useRouter();
  const user = useUserStore();

  let interval = null;
  let switcher = null;
  let notice = ref('欢迎使用iAccount账本！');
  let notice_list = reactive([]);
  function* switchNotice() {
    const len = notice_list.length;
    let cur = 0;
    while(1) {
      if(cur === len) cur = 0;
      yield notice_list[cur++];
    }
  }
  const checkNotice = () => {
    message.confirm(notice_list.join('；'), "公告", "info");
  };

  const menu = [
    {
      name: "记收入",
      icon: "#icon-qian",
      color: "#20a162",
      navigation() {
        router.push('/p/income');
      }
    },
    {
      name: "记支出",
      icon: "#icon-jijianfasong",
      color: "#1177b0",
      navigation() {
        router.push('/p/expense');
      }
    },
  ];

  const now = new Date();
  let loadingCard = ref(true);
  let date = `${ now.getFullYear() }-${ now.getMonth() + 1 }-${ now.getDate() }`;
  let myChart = null;
  const option = reactive({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '日占月支出',
        type: 'pie',
        radius: ['35%', '55%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        tooltip: {
          confine: true
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: '---', name: '当月总支出' },
          { value: '---', name: '今日总支出' },
        ]
      }
    ]
  });

  let todayIncome = ref('---');
  let monthIncome = ref('---');
  const createNotice = () => {
    notice_list.push(`今日收入：￥${todayIncome.value}，再接再厉哦~`);
    if(option.series[0].data[1].value >= 300)
      notice_list.push(`今日支出大于￥300，请注意！`);
    notice_list.push(`今日收入/当月收入：${Math.floor(todayIncome.value/monthIncome.value*100)}%`);
    notice_list.push('其它功能敬请期待...');
  }
  onMounted(() => {
    getTodayInfo(user.userID)
      .then(res => {
        if(res.data.msg === "成功") {
          option.series[0].data[1].value = res.data.data[1]; // 今日总支出
          todayIncome.value = res.data.data[0]; // 今日总收入
          getMonthInfo(user.userID)
            .then(res => {
              if(res.data.msg === "成功") {
                option.series[0].data[0].value = res.data.data[1]; // 当月总支出
                monthIncome.value = res.data.data[0]; // 当月总收入
                createNotice();                
                switcher = switchNotice();
                interval = setInterval(() => {
                  notice.value = switcher.next().value;
                }, 4000);
                // 绘图
                myChart = echarts.init(document.getElementById('dayPercent'));
                myChart.setOption(option);
                window.addEventListener('resize', () => {
                  myChart.resize();
                });
                loadingCard.value = false;
              } else {
                message.warning('获取信息失败');
              }
            })
            .catch(err => {
              message.warning('系统错误，请重试');
              console.warn(err);
            });
        } else {
          message.warning('获取信息失败');
        }
        console.log(res.data);
      })
      .catch(err => {
        message.warning('系统错误，请重试');
        console.warn(err);
      });
  });
  onBeforeUnmount(() => {
    clearInterval(interval);
  });
</script>

<style lang="scss" scoped>
  .notice-container{
    width: 92%;
    height: 45px;
    margin: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    .notice-box{
      width: 100%;
      line-height: 30px;
      background-color: antiquewhite;
      border-radius: 8px;
      color: brown;
      font-size: 15px;
      cursor: pointer;
      svg{
        margin-left: 12px;
        margin-right: 5px;
      }
    }
  }
  .title-imgs-container{
    width: 92%;
    height: 200px;
    margin: auto;
    border-radius: 8px;
    overflow: hidden;
    background-color: $theme-shadow0;
    .title-img{
      width: 100%;
      height: 200px;
    }
  }
  .menu-list-container{
    width: 92%;
    margin: auto;
    margin-top: 15px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    .menu-item{
      width: 45%;
      line-height: 60px;
      text-align: center;
      margin-bottom: 15px;
      border-radius: 15px;
      font-size: 20px;
      letter-spacing: 5px;
      color: white;
      box-shadow: 1px 1px 6px $theme-shadow0;
      cursor: pointer;
      svg{
        margin-right: 8px;
      }
    }
  }
  .bottom-tips{
    width: fit-content;
    line-height: 20px;
    margin: auto;
    margin-top: 20px;
    font-size: 13px;
    color: $theme-shadow;
    user-select: none;
  }
  .status-card{
    position: relative;
    width: 92%;
    height: 200px;
    margin: auto;
    border-radius: 8px;
    background-color: white;
    overflow: hidden;
    box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.04), 0 4px 8px 8px rgba(0, 0, 0, 0.04), 0 4px 8px 0 rgba(0, 0, 0, 0.08);
    .status-content{
      float: right;
      width: 55%;
      height: 100%;
      .today-income{
        height: 79px;
        width: 100%;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        border-bottom: 1px solid $theme-shadow00;
      }
      .today-expense{
        height: 80px;
        width: 100%;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
      }
      .family-more{
        height: 40px;
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        justify-content: center;
        .more-txt{
          line-height: 30px;
          color: $theme-shadow;
          font-size: 14px;
          cursor: pointer;
        }
        .more-txt:hover{
          color: $theme-main;
        }
      }
    }
    .today-title{
      line-height: 20px;
      width: 100%;
      margin-top: 8px;
      text-align: center;
      span{
        color: $theme-main-dark;
        font-size: 17px;
        font-weight: 550;
        border-bottom: 2px solid $theme-main;
        user-select: none;
      }
    }
    .today-num{
      line-height: 40px;
      width: 100%;
      text-align: center;
      font-size: 20px;
    }
    .date-box{
      position: absolute;
      bottom: 0;
      left: 0;
      width: 45%;
      line-height: 30px;
      text-align: center;
      border-top-right-radius: 5px;
      background-color: $theme0;
      color: white;
    }
  }
  #dayPercent{
    float: left;
    width: 45%;
    height: 100%;
  }
</style>